try:
    import abc_decoder
except:
    import decoders.abc_decoder as abc_decoder

import pydub 
import pandas as pd
import numpy as np

def get_class():
    'None 表示这是抽象基类'
    return mp3_decoder

class mp3_decoder(abc_decoder.abs_decoder):
    def __init__(self):
        self.strFormat = 'mp3'
    def get_name(self):
        return 'mp3 decoder'            
    def decode(self, file_path:str, **kwargs):        
        #todo: decode mp3 and return numpy array
        # each channel should be one dimension
        try:
            column_keys = kwargs['column_keys']
        except:
            column_keys = ['ax', 'ay']
        print('decoding %s file: %s' % (self.strFormat, file_path))

        """----------读取mp3格式信息----------"""
        a = pydub.AudioSegment.from_mp3(file_path)   #  AudioSegment读取mp3文件
        # print(a)
        nchannels = a.channels   # nchannels通道数 = 2
        framerate = a.frame_rate    # framerate采样频率 = 48000
        nframes = int(a.frame_count())    # 采样点数 = 617400
        str_data = a.raw_data    # str_data二进制的, 而get_array_of_samples()返回正常数值

        """----------MP3 to numpy array----------"""
        a = pydub.AudioSegment.from_mp3(file_path)   
        # print(a.get_array_of_samples())
        y = np.array(a.get_array_of_samples())    #  get_array_of_samples()函数将mp3文件读为数组
        #  频道数只有0和1，即左声道和右声道
        if a.channels == 2:    
            y = y.reshape((-1, 2))
        #  即对采样点数进行归一化操作
        normalized=False
        if normalized:    
            y = np.float32(y) / 2**15
        else:
            y = y / 2**8

        """----------通过采样点数和取样频率计算出每个取样的时间----------"""
        time = np.arange(0, nframes) * (1.0 / framerate)
        time = np.round(time, 5)

        """----------生成csv文件----------"""
        data = y
        dict_data = {'mp3_data1': data[:, 0], 'mp3_data2': data[:, 1]}
        dataframe = pd.DataFrame(dict_data, index=list(time))
        # dataframe.to_csv("mp3_to_np.csv", index=True, sep=',')
        
        # mp3_data1 = data[:, 0]
        # mp3_data2 = data[:, 1]
        # ret = [mp3_data1, mp3_data2]
        if (column_keys[0] != 'leftChn') & (column_keys[1] != 'rightChn'):
            retMp3 = data
        elif (column_keys[0] == 'leftChn') & (column_keys[1] != 'rightChn'):
            retMp3 = data[:, 0]
        elif (column_keys[0] != 'leftChn') & (column_keys[1] == 'rightChn'):
            retMp3 = data[:, 1]
        else:
            retMp3 = data

        return retMp3